const moment = require('moment')
const Store = require('../../model/Store')
const Dish = require('../../model/Dish')
const Activity = require('../../model/Activity')
const async = require('async')
const request = require('request')
const miniappAccessToken = require('../../util/businessUtil/miniappAccessToken')
const TencentID = 'AKIDacOtBFLv7T5TghNTZR5Tbgw87sPph4nJ'
const TencentPWD = 'Zo4ACzvnV5ZDheNp1yg8wT1Pbu52kEUB'
const COS = require('cos-nodejs-sdk-v5');
const cos = new COS({
    SecretId: TencentID,
    SecretKey: TencentPWD
});
var fs = require('fs')

module.exports = {

    //获取日志列表
    changeStore: async(req, res, next) => {
        try {

            let count = await Store.countDocuments({ isDelete: 0 }).exec()
                // return console.log(req.body)
            if (req.body.id) {
                let store = await Store.findOne({ _id: req.body.id, isDelete: 0 }).exec()
                store.name = req.body.name,
                    store.brief = req.body.brief,
                    store.detail = req.body.detail,
                    store.address = req.body.address,
                    store.city = req.body.city,
                    store.district = req.body.district,
                    store.hours = req.body.hours,
                    store.contact = req.body.contact,
                    store.label = req.body.label,
                    store.location = req.body.location,
                    store.images = req.body.images,
                    store.attribute = req.body.attribute,
                    store.recommendActivity = req.body.recommendActivity,
                    store.status = req.body.status,
                    store.takeawayMenu = req.body.takeawayMenu,
                    store.index = req.body.index || (count + 1),
                    store.addressEN = req.body.addressEN,
                    store.attributeVIP = req.body.attributeVIP
                await store.save()
                let oldDishList = (await Dish.find({ store: { $in: req.body.id }, isDelete: 0 }, '_id').exec()).map(e => { return String(e._id) })
                async.each(req.body.dish, async function(item, callback) {
                    let index = oldDishList.indexOf(item)
                    if (index == -1) {
                        let dish = await Dish.findOne({ _id: item, isDelete: 0 }).exec()
                        dish.store.push(req.body.id)
                        dish.markModified('store')
                        await dish.save()
                    }
                })
                async.each(oldDishList, async function(item, callback) {
                    let index = req.body.dish.indexOf(item)
                    if (index == -1) {
                        let dish = await Dish.findOne({ _id: item, isDelete: 0 }).exec()
                        let dishIndex = dish.store.indexOf(req.body.id)
                        dish.store.splice(dishIndex, 1)
                        dish.markModified('store')
                        await dish.save()
                    }
                })
                let oldActivityList = (await Activity.find({ store: { $in: req.body.id }, isDelete: 0 }, '_id').exec()).map(e => { return String(e._id) })
                async.each(req.body.recommendActivity, async function(item, callback) {
                    let index = oldActivityList.indexOf(item)
                        // console.log(oldActivityList, item, index)
                    if (index == -1) {
                        let activity = await Activity.findOne({ _id: item, isDelete: 0 }).exec()
                        activity.store.push(req.body.id)
                        activity.markModified('store')
                        await activity.save()
                    }
                })
                async.each(oldActivityList, async function(item, callback) {
                    let index = req.body.recommendActivity.indexOf(item)
                    if (index == -1) {
                        let activity = await Activity.findOne({ _id: item, isDelete: 0 }).exec()
                        let activityIndex = activity.store.indexOf(req.body.id)
                        activity.store.splice(activityIndex, 1)
                        activity.markModified('store')
                        await activity.save()
                    }
                })
                if (req.body.index) {
                    tempStore = await Store.find({ _id: { $ne: store._id }, index: { $gte: store.index }, isDelete: 0 }).sort({ index: 1 }).exec()
                    tempStore.forEach(async(e, index) => {
                        e.index = store.index + index + 1
                        await e.save()
                    });
                }
                miniappAccessToken.getAccessToken(function(token) {
                    request({
                             url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + token,
                             method: "POST",
                             timeout: 10000,
                             encoding: null,
                             body:JSON.stringify({
                                 "access_token":token,
                                "path":"pages/storeDetail/storeDetail?id="+store._id + "&way=storeQR"
                               }),
                         },function(error, response, body){
                             cos.putObject({
                                 Bucket: 'beamuse-1301730110',
                                 Region: 'ap-shanghai',
                                 Key: '/image/' + store._id+'QR.jpg', // 这里传入前缀
                                 Body: body,
                             }, function(err, data) {
                                store.storeQR = data.Location
                                store.save()
                                //  console.log(err);
                                //  console.log(data.Location)
                             });
                    })
                })
                miniappAccessToken.getAccessToken(function(token) {
                    request({
                             url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + token,
                             method: "POST",
                             timeout: 10000,
                             encoding: null,
                             body:JSON.stringify({
                                 "access_token":token,
                                "path":"pages/storeDetail/storeDetail?id="+store._id + "&way=publicStoreQR"
                               }),
                         },function(error, response, body){
                             cos.putObject({
                                 Bucket: 'beamuse-1301730110',
                                 Region: 'ap-shanghai',
                                 Key: '/image/' + store._id+'publicStoreQR.jpg', // 这里传入前缀
                                 Body: body,
                             }, function(err, data) {
                                store.publicStoreQR = data.Location
                                store.save()
                                //  console.log(err);
                                //  console.log(data.Location)
                             });
                    })
                })
                return res.ok('修改成功', store)

            } else if (!req.body.id) {
                // console.log('add')
                let newStore = new Store({
                    name: req.body.name,
                    brief: req.body.brief,
                    detail: req.body.detail,
                    address: req.body.address,
                    city: req.body.city,
                    district: req.body.district,
                    hours: req.body.hours,
                    contact: req.body.contact,
                    label: req.body.label,
                    location: req.body.location,
                    images: req.body.images,
                    attribute: req.body.attribute,
                    isDelete: 0,
                    recommendActivity: req.body.recommendActivity,
                    takeawayMenu: req.body.takeawayMenu,
                    status: 0,
                    index: req.body.index,
                    addressEN:req.body.addressEN,
                    attributeVIP:req.body.attributeVIP
                })
                await newStore.save()
                async.each(req.body.dish, async function(item, callback) {
                    let dish = await Dish.findOne({ _id: item, isDelete: 0 }).exec()
                    dish.store.push(newStore._id)
                    dish.markModified('store')
                    await dish.save()
                })
                async.each(req.body.recommendActivity, async function(item, callback) {
                    let activity = await Activity.findOne({ _id: item, isDelete: 0 }).exec()
                    activity.store.push(newStore._id)
                    activity.markModified('store')
                    await activity.save()
                })
                if (req.body.index) {
                    tempStore = await Store.find({ index: { $gte: req.body.index }, isDelete: 0 }).sort({ index: 1 }).exec()
                    tempStore.forEach(async(e, index) => {
                        e.index = req.body.index + index + 1
                        await e.save()
                    });
                }
                miniappAccessToken.getAccessToken(function(token) {
                    request({
                             url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + token,
                             method: "POST",
                             timeout: 10000,
                             encoding: null,
                             body:JSON.stringify({
                                 "access_token":token,
                                "path":"pages/storeDetail/storeDetail?id="+newStore._id + "&way=storeQR"
                               }),
                         },function(error, response, body){
                             cos.putObject({
                                 Bucket: 'beamuse-1301730110',
                                 Region: 'ap-shanghai',
                                 Key: '/image/' + newStore._id+'QR.jpg', // 这里传入前缀
                                 Body: body,
                             }, function(err, data) {
                                newStore.storeQR = data.Location
                                newStore.save()
                                //  console.log(err);
                                //  console.log(data.Location)
                             });
                    })
                })
                miniappAccessToken.getAccessToken(function(token) {
                    request({
                             url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + token,
                             method: "POST",
                             timeout: 10000,
                             encoding: null,
                             body:JSON.stringify({
                                 "access_token":token,
                                "path":"pages/storeDetail/storeDetail?id="+store._id + "&way=publicStoreQR"
                               }),
                         },function(error, response, body){
                             cos.putObject({
                                 Bucket: 'beamuse-1301730110',
                                 Region: 'ap-shanghai',
                                 Key: '/image/' + store._id+'publicStoreQR.jpg', // 这里传入前缀
                                 Body: body,
                             }, function(err, data) {
                                store.publicStoreQR = data.Location
                                store.save()
                                //  console.log(err);
                                //  console.log(data.Location)
                             });
                    })
                })
                return res.ok('创建成功', newStore)
            }
        } catch (e) {
            next(e)
        }
    },


    deleteStore: async(req, res, next) => {
        try {
            let store = await Store.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            store.isDelete = 1
            await store.save()
            return res.ok('删除成功', store)
        } catch (e) {
            next(e)
        }
    },


    getStoreList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.name) {
                option.name = new RegExp(req.body.name, 'i')
            }
            if (req.body.address) {
                option.address = new RegExp(req.body.address, 'i')
            }
            // console.log(req.session.user)
            if (req.session.user != undefined && req.session.user.store.length != 0) {
                option._id = req.session.user.store
            }
            let count = await Store.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Store.find(option).skip((page - 1) * pageSize).limit(pageSize).sort({ index: 1 }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },


    getOneStore: async(req, res, next) => {
        let data = {}
        data.dish = await Dish.find({ store: { $in: req.body.id }, isDelete: 0 }).exec()
        data.store = await Store.findOne({ _id: req.body.id, isDelete: 0 }).populate('recommendActivity').exec()
        data.recommendActivity = data.store.recommendActivity
        res.ok('获取成功', data)
    },


    storeOnline: async(req, res, next) => {
        store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
        store.status = 1
        await store.save()
        res.ok('上线成功')
    },


    storeOffline: async(req, res, next) => {
        store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
        store.status = 0
        await store.save()
        res.ok('下线成功')
    },

    storeRankingRise: async(req, res, next) => {
        store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
        tempStore = await Store.find({ _id: { $ne: req.body.store }, index: { $gte: store.index - 1 }, isDelete: 0 }).sort({ index: 1 }).exec()
        tempStore.forEach(async(e, index) => {
            e.index = store.index + index
            await e.save()
        });
        store.index = store.index - 1
        await store.save()
        res.ok('升序成功')
    },

    storeRankingDrop: async(req, res, next) => {
        store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
        store.index = store.index + 1
        await store.save()
        nextStore = await Store.findOne({ index: store.index, isDelete: 0 }).exec()
        if (nextStore) {
            nextStore.index = store.index - 1
            await nextStore.save()
        }
        tempStore = await Store.find({ _id: { $ne: req.body.store }, index: { $gte: store.index }, isDelete: 0 }).sort({ index: 1 }).exec()
        tempStore.forEach(async(e, index) => {
            // console.log(store.index, e._id, e.index, index)
            e.index = store.index + index + 1
            await e.save()
        });
        res.ok('降序成功')
    },

};